﻿// -----------------------------
// Copyright © Kodi Studios 2012
// -----------------------------

using System;
using System.Net;
using System.Text.RegularExpressions;

namespace Kodi.Picturethrill
{
    public static class HtmlUtilities
    {
        public static string GetImageUrl(string websiteUrl, Regex urlRegex)
        {
            WebClient webClient = new WebClient();
            string pageHtml = string.Empty;
            try
            {
                pageHtml = webClient.DownloadString(websiteUrl);
            }
            catch (Exception)
            {
//#if DEBUG 
//                throw;
//#endif
                // Would be nice to log here or send a report :)
                return string.Empty;
            }

            if (urlRegex.IsMatch(pageHtml))
            {
                string imgPath = urlRegex.Match(pageHtml).Groups[1].Value;
                if (imgPath.StartsWith("http"))
                {
                    return imgPath;
                }

                // Relative to website Url
                string imageUrl = websiteUrl;

                imageUrl = imageUrl.TrimEnd('/');
                imgPath = imgPath.TrimStart('/');

                imageUrl += "/" + imgPath;
                return imageUrl;
            }

            return string.Empty;
        }
    }
}
